class BabyService {

  boolean transactional = true
  def authenticateService
  
  def getStage(Baby baby) {
    def today = new Date()
    if (baby.birth) {
      return (20000 + (today - baby.birth))
    } else if (baby.datePregnant) {
      return (10000 + (today - baby.datePregnant))
    } else {
      return 0
    }
  }

  def calcExpectedBirth(Date datePregnant) {
    return datePregnant + 280
  }

  def say() {
    println "hello"
  }

  def paln2Task(Baby baby) {
    def stage = getStage(baby)
    def start = (stage - 14) > 0 ? (stage - 14) : 0
    def end = stage + 14
    def planList = Plan.findAllByStartWithBetween(start, end)
    planList.each {
      println it.name
      def chs = Task.findAllByPlanId(it.id)
      if (!chs) {
        def task = new Task()
        task.title = it.name
        task.baby = baby
        task.content = it.description
        task.taskType = it.planType
        task.planId = it.id
        task.reminded = new Integer(0)
        task.dateActive = (new Date()) + (it.startWith - getStage(baby))
        task.status = Task.TASK_STATUS_NOT_READ
        task.save()
      }
    }
  }



  def getNews(Date lastVisited) {
    def model = [:]
    def rootCatalog = Catalog.findByName("news")
    if (rootCatalog) {
      def total = Entry.countByRootCatalogIdAndDateCreatedGreaterThan(rootCatalog.id, lastVisited)
      if (total > 0) {
        def entryList = Entry.findAllByRootCatalogIdAndDateCreatedGreaterThan(rootCatalog.id, lastVisited, [max: 10], sort: 'desc', order: 'dateCreated')
        model.entryList = entryList
        model.total = total
        return model
      }
    }
    model.entryList = []
    model.total = 0
    return model

  }

  def getLessons(Integer stage, Long lastEntryId){

  }

  def getMyEvents(Baby baby){
    def enventList = Event.findAllByBaby(baby, [max:10,sort:'desc', order:'dateCreated'])
    

  }


  def getSameStageBabies(Date birth){

  }


  def finishTask(Task task){
    task.status = Task.TASK_STATUS_DONE
    task.dateUpdate = new Date()
    task.save()
    def event = new Event()
    event.title = task.title
    event.content = task.content
    event.read = true
    event.baby = task.baby
    event.save()
  }

  def isManager(Baby baby){
    def p = authenticateService.userDomain()
    if(baby && p){
      if(baby.person.id == p.id){
        return true
      }
    }    
  }


}
